package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import Models.POSGlassWare;

public class POSGlassWarePresenter extends AbstractPresenter<POSGlassWare> {
	final String SINGLEITEM = "posGlassWare";
	final String MULTIITEM = "pOSGlassWares";
	
	public ArrayList<POSGlassWare> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public POSGlassWare tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public POSGlassWare createItemFromJSONObject(JSONObject jsonGlassware){
		POSGlassWare glassware = new POSGlassWare();
		try{
			glassware.setDescription(jsonGlassware.getString("glassWareDescription"));
			glassware.setId(jsonGlassware.getInt("id"));
			glassware.setPackageSize(jsonGlassware.getDouble("size"));
			glassware.setPrePackaged(jsonGlassware.getBoolean("prePackaged"));
			glassware.setRefillable(jsonGlassware.getBoolean("refillable"));
			glassware.setLoyaltyGrowler(jsonGlassware.getBoolean("loyaltyGrowler"));
			glassware.setLoyaltyPoints(jsonGlassware.getBoolean("loyaltyPoints"));
			if(!jsonGlassware.isNull("supply")){
				//create discount if set
				POSSupplyViewPresenter supplyPresenter = new POSSupplyViewPresenter();
				JSONObject jsonItem = jsonGlassware.getJSONObject("supply");
				glassware.setSupply(supplyPresenter.createItemFromJSONObject(jsonItem));
			} else {
				glassware.setSupply(null);
			}
			return glassware;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(POSGlassWare item){
		try{
			JSONObject json = new JSONObject();
			json.put("glassWareDescription", item.getDescription());
			json.put("id", item.getId());
			json.put("size", item.getPackageSize());
			json.put("prePackaged", item.isPrePackaged());
			json.put("refillable", item.isRefillable());
			json.put("loyaltyGrowler", item.isLoyaltyGrowler());
			json.put("loyaltyPoints", item.isLoyaltyPoints());
			if(item.getSupply()!=null){
				final POSSupplyViewPresenter supplyPresenter = new POSSupplyViewPresenter();
				json.put("supply", supplyPresenter.createJSON(item.getSupply()));
			} else {
				json.put("supply", JSONObject.NULL);
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSGlassWare getEmptyEntity(){
		POSGlassWare entity = new POSGlassWare();
		return entity;
	}
}
